package org.novelhibernate.core.connection;

import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.novelhibernate.core.transaction.Transaction;
import org.novelhibernate.core.transaction.TransactionImpl;


/**
 * 
 * This is the DataSource-driven connection factory, which acquire connection
 * from DataSource
 * 
 * 
 * @author Tao Chen
 *
 */
public class DataSourceTransactionFactory implements ConnectionFactory {

	private DataSource dataSource;
	private static DataSourceTransactionFactory factory;


	
	private DataSourceTransactionFactory() {
	
	}

	
	public static DataSourceTransactionFactory getInstance(){
		
		if(null == factory)
			factory = new DataSourceTransactionFactory();
		
		return factory;
	}
	
	/**
	 * Configure the factory by given data source
	 * @param dataSource The DataSource that connection manager will use to get new
	 *                   database connection.
	 */
	public void config(DataSource dataSource) {
		
		this.dataSource = dataSource;
	
	}  
	
	/**
	 * Configure the factory by given naming key
	 * @param name naming key that used to look up data source.
	 * @throws NamingException 
	 */
	public void config(String name) throws NamingException {
		
		Context c = new InitialContext();
		this.dataSource = (DataSource) c.lookup(name);
	
	}
	
	@Override
	public Transaction createTransaction(boolean autoCommit,
			int transactionIsolation, boolean isRecordResult) throws SQLException {
		
		return new TransactionImpl(dataSource.getConnection(), autoCommit, transactionIsolation, isRecordResult);
	}



}
